var async = require('async');
var moment = require('moment');

var connPool = require('./connPool.js');
var LoginBean = require('../jsBean/LoginBean');
var Result = require('../jsBean/Result');

module.exports = {
	search: function (req, res, loginbean) {
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				res.send('getConnection ERROR');
				return;
			}
			 
			
			var selectNewsSql = 'SELECT title FROM news WHERE title LIKE "%';
			selectNewsSql += req.body['content'];
			selectNewsSql += '%" ORDER BY click DESC LIMIT 6;';
			var param = [];
			
			conn.query(selectNewsSql, param, function (err, rs) {
				if(err) {
					console.log(err.message);
					
					return;
				}
				
				conn.release();
				
				var result = new Result();
				result.status = 1;
				result.data = rs;
				
				res.send(result);
			});
		});
	},
	
	moreNews: function (req, res, loginbean) {
		// 转换时间戳格式
		function timeTransform (time) {
			return moment(time).format('YYYY-MM-DD HH:mm:ss');
		}
		
		var classify = req.query['classify'];
		var content = req.query['content'];
		
		var pool = connPool();
		
		pool.getConnection(function (err, conn) {
			if(err) {
				console.log(err.message);
				
				return;
			}
			 
			if(classify == 'all') {
				var selectNewsSql = "SELECT n.*, u.name FROM news AS n JOIN user AS u ON n.sendCount=u.account WHERE n.title LIKE \'%";
				selectNewsSql += content;
				selectNewsSql += "%\' ORDER BY click DESC;";
				var param = [];
				
				conn.query(selectNewsSql, param, function (err, rs) {
					if(err) {
						console.log(err.message);
						
						return;
					}
					
					conn.release();
					
					var searchNews = rs;
					searchNews.forEach(function (item) {
						item.sendTime = timeTransform(item.sendTime);
					});
					res.render('more', {
						loginbean: loginbean,
						searchNews: searchNews,
						classify: classify
					});
				});
			}else {
				var selectNewsSql = 'SELECT n.*, u.name FROM news AS n JOIN user AS u ON n.sendCount=u.account WHERE n.classify=? AND n.title LIKE "%';
				selectNewsSql += content;
				selectNewsSql += '%" ORDER BY click DESC;';
				var param = [classify];
				
				conn.query(selectNewsSql, param, function (err, rs) {
					if(err) {
						console.log(err.message);
						
						return;
					}
					
					conn.release();
					
					var searchNews = rs;
					searchNews.forEach(function (item) {
						item.sendTime = timeTransform(item.sendTime);
					});
					res.render('more', {
						loginbean: loginbean,
						searchNews: searchNews,
						classify: classify
					});
				});
			}
		});
	}
};
